package com.partsoft.dits.dsm;

import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

public class ResourceDsmSQLProviderFactory extends AbstractDsmSQLProviderFactory implements InitializingBean {

	protected ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver();

	private List<String> dsmOriginalSqlLocations = new LinkedList<String>();

	public ResourceDsmSQLProviderFactory() {
	}

	public ResourceDsmSQLProviderFactory(List<String> dsmOriginalSqlLocations) {
		setDsmOriginalSqlLocations(dsmOriginalSqlLocations);
		try {
			afterPropertiesSet();
		} catch (Throwable e) {
			throw new IllegalArgumentException(e.getMessage(), e);
		}
	}
	
	public ResourceDsmSQLProviderFactory(String[] dsmOriginalSqlLocations) {
		this(Arrays.asList(dsmOriginalSqlLocations));
	}
	
	public ResourceDsmSQLProviderFactory(String dsmOriginalSqlLocation) {
		this(new String[]{dsmOriginalSqlLocation});
	}

	protected List<String> getDsmOriginalSqlLocations() {
		synchronized (this) {
			if (dsmOriginalSqlLocations == null || dsmOriginalSqlLocations.equals(Collections.EMPTY_LIST)) {
				dsmOriginalSqlLocations = new LinkedList<String>();
			}
			return dsmOriginalSqlLocations;
		}
	}

	public void setDsmOriginalSqlLocations(List<String> dsmOriginalSqlLocations) {
		this.dsmOriginalSqlLocations = dsmOriginalSqlLocations;
	}

	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	public void addDsmOriginalSQLs(String dsmOriginalSqlLocation) {
		getDsmOriginalSqlLocations().add(dsmOriginalSqlLocation);
	}

	public void afterPropertiesSet() throws Exception {
		List<InputStream> ims = new LinkedList<InputStream>();
		try {
			for (String location : getDsmOriginalSqlLocations()) {
				try {
					InputStream ism = resourceLoader.getResource(location).getInputStream();
					ims.add(ism);
					addDsmOriginalSQLs(ism);
				} catch (Throwable e) {
					String esm = String.format("occur an error when parse file \"%s\": %s", location, e.getMessage());
					throw new IllegalArgumentException(esm, e);
				}
			}
		} finally {
			for (InputStream ism : ims) {
				IOUtils.closeQuietly(ism);
			}
		}
	}
	
}
